package com.example.dzl.aoptest.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

/**
 * @author 光的代言人
 */
@Slf4j
@Aspect
@Component
public class LogAspect {
    /**
     * 拦截 com.example.dzl.aoptest.service.UserService 所有方法
     */
    @Pointcut("execution(* com.example.dzl.aoptest.service.UserService.*(..))")
    public void userServiceMethod(){

    }
//    /**
//     * 前置通知
//     * @param joinPoint
//     */
//    @Before("userServiceMethod()")
//    public void before(JoinPoint joinPoint){
//        log.info("日志，开始执行 {} 方法",joinPoint.getSignature().getName());
//    }
//    /**
//     * 后置通知
//     * @param joinPoint
//     */
//    @After("userServiceMethod()")
//    public void after(JoinPoint joinPoint){
//        log.info("日志，结束执行 {} 方法",joinPoint.getSignature().getName());
//    }

    @Around("userServiceMethod()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        log.info("日志，开始执行 {} 方法", joinPoint.getSignature().getName());

        long startTime = System.currentTimeMillis();
        Object result = null;
        try {
            // 执行目标方法
            result = joinPoint.proceed();
            return result;
        } catch (Exception e) {
            log.error("方法执行异常: {}", e.getMessage());
            throw e;
        } finally {
            long endTime = System.currentTimeMillis();
            log.info("日志，结束执行 {} 方法，耗时 {}ms", joinPoint.getSignature().getName(), (endTime - startTime));
        }
    }

    @AfterReturning(value = "userServiceMethod()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        log.info("方法 {} 执行成功，返回值：{}", joinPoint.getSignature().getName(), result);
    }

    @AfterThrowing(value = "userServiceMethod()", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Exception ex) {
        log.error("方法 {} 执行失败，抛出异常: {}", joinPoint.getSignature().getName(), ex.getMessage());
    }
}
